package cn.virens.common.boot.rabbit.channel;

import cn.virens.common.boot.rabbit.autoconfig.RabbitManageProperties;
import cn.virens.common.util.exception.APIException;
import cn.virens.common.util.exception.ExceptionUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ChannelListener;
import org.springframework.beans.factory.InitializingBean;

import java.io.IOException;

public class SimpleChannelListener implements ChannelListener, InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(SimpleChannelListener.class);
    private final RabbitManageProperties properties;
    private final CachingConnectionFactory factory;

    public SimpleChannelListener(RabbitManageProperties properties, CachingConnectionFactory factory) {
        this.properties = properties;
        this.factory = factory;
    }

    private void onCreate0(Channel channel, boolean transactional) throws APIException, IOException {
        channel.basicQos(properties.getPrefetchSize(), properties.getPrefetchCount(), true);
    }

    @Override
    public void onCreate(Channel channel, boolean transactional) throws APIException {
        ExceptionUtil.safe2(log, channel, (c) -> onCreate0(c, transactional));
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.factory.addChannelListener(this);
    }
}
